<template>
  <div class="body" v-if="options">
    <el-form :model="model" label-width="80px" @submit.prevent>
      <el-form-item
        v-for="option of options.items"
        :key="option.prop"
        :label="`${option.label} :`"
      >
        <edit-item :option="option"></edit-item>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm" native-type="submit"
          >提交</el-button
        >
        <el-button @click="$router.go(-1)">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { ElIcon, ElMessage, ElForm, ElFormItem, ElButton } from "element-plus";
import { defineComponent, toRefs, watchEffect } from "vue";

import { router } from "../../router";
import { useOptions } from "../../hooks/useOptions.hook";
import { useModel } from "../../hooks/useModel.hook";
import EditItem from "../../components/EditItem.vue";

export default defineComponent({
  name: "Edit",
  components: {
    ElIcon,
    ElForm,
    ElFormItem,
    ElButton,
    EditItem,
  },
  setup(props) {
    const { resource, id } = toRefs(props);
    const { options, getOptions } = useOptions(resource?.value);
    const { model, findModel, createModel, updateModel } = useModel(
      resource?.value
    );

    watchEffect(async () => {
      await getOptions();
      id?.value && (await findModel(id?.value));
      options.value.items.forEach((i) => {
        if (i.sub) {
          i.value = model.value[i.prop][i.sub];
        } else {
          i.value = model.value[i.prop];
        }
      });
    });

    async function submitForm() {
      try {
        options.value.items.forEach((i) => {
          if (i?.sub) {
            model.value[i.prop][i.sub] = i.value;
          } else {
            model.value[i.prop] = i.value;
          }
        });
        if (id.value) {
          await updateModel(id.value, model.value);
        } else {
          await createModel();
        }
        ElMessage.success("提交成功");
        router.go(-1);
      } catch (e) {
        ElMessage.error("请检查输入字段");
      }
    }

    return {
      options,
      getOptions,
      model,
      findModel,
      submitForm,
    };
  },
  props: {
    resource: String,
    id: String,
  },
});
</script>

<style lang="scss">
.body {
  background: #fff;
  margin: 10px;
  padding: 20px;
  border: 1px solid rgba(0, 0, 0, 0.15);
}
</style>
